package lesson03.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoServer01 {
    protected ServerSocket socket;

    public TCPEchoServer01(int port) throws IOException {
        if (port < 1024 || port > 65535) {
            throw new BindException("端口号需要在1024 - 65535之间");
        }
        socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器已启动，等待客户端连接.");
        while (true) {
            Socket Clinetaccept = socket.accept();
            processConnection(Clinetaccept);
        }

    }

    protected void processConnection(Socket clinetaccept) {
        System.out.printf("[%s:%d] 客户端上线了.\n", clinetaccept.getInetAddress().toString(), clinetaccept.getPort());
        try (InputStream inputStream = clinetaccept.getInputStream();
             OutputStream outputStream = clinetaccept.getOutputStream()) {
            while (true) {
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNextLine()) {
                    System.out.printf("[%s:%d] 客户端下线了.\n", clinetaccept.getInetAddress().toString(), clinetaccept.getLocalPort());
                    break;
                }
                String request = scanner.nextLine();
                String response = process(request);

                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                writer.flush();
                System.out.printf("[%s:%d] request = %s  response = %s\n",
                        clinetaccept.getInetAddress().toString(), clinetaccept.getPort(), request, response);


            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer01 tcpEchoServer = new TCPEchoServer01(9090);
        tcpEchoServer.start();
    }
}
